<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="./js/requset.js"></script>
  <script src="./js/cookie.js"></script>
</head>

<body>
  <h1>用户修改页面</h1>
  <form action="">
    头像：
    <img src="" alt="">
    <input type="file" name='avatar'>
    <br>
    用户名：<input type="text" name="username">
    <br>
    邮箱：<input type="email" name="email">
    <br>
    <input type="submit">
  </form>
</body>
<script>
  // 获取标签
  var usernameInput = document.querySelector('[name="username"]')
  var emailInput = document.querySelector('[name="email"]')
  var avatarInput = document.querySelector('[name="avatar"]')
  // 发请求获取用户信息展示在表单中
  request({
    url: '/user/info/' + getCookie('userid'),
    headers: {
      Authorization: localStorage.getItem('token')
    }
  }).then(res => {
    console.log(res);
    usernameInput.value = res.data.username
    emailInput.value = res.data.email
    document.querySelector('img').src = res.data.avatar
  })

  document.querySelector('form').onsubmit = function () {
    var username = usernameInput.value
    var email = emailInput.value
    console.dir(avatarInput);
    // ajax要提交数据带有文件信息 - formData
    var formdata = new FormData()
    formdata.append('username', username)
    formdata.append('email', email)
    formdata.append('avatar', avatarInput.files[0])

    request({
      url: '/user/editUser/' + getCookie('userid'),
      method: 'put',
      data: formdata,
      headers: {
        Authorization: localStorage.getItem('token')
      }
    }).then(res => {
      console.log(res);
    })
    return false
  }
</script>

</html>